<?php
declare (strict_types=1);

namespace app\middleware;

use app\service\alone\Cache\RedisService;
use app\service\traits\Unified;

class ApiLock
{
    use Unified;

    /**
     * 处理请求
     *
     * @param $request
     * @param \Closure $next
     * @return \think\Response
     */
    public function handle($request, \Closure $next)
    {
        // 路由
        $route = app('http')->getName() . '-' . $request->rule()->getName();

        // 锁
        if (!$lock = RedisService::getInstance()->set($route, 1, 30)) return $this->returnResponse(500, '请勿重复调用该接口');

        // 处理请求
        $response = $next($request);

        // 关闭锁
        RedisService::getInstance()->clear($route);

        return $response;
    }

    /**
     * 返回数据
     *
     * @param $code
     * @param $msg
     * @return \think\Response|\think\response\Redirect
     */
    private function returnResponse($code, $msg)
    {
        if (request()->isAjax()) return $this->returnData($code, $msg);

        return redirect((string)url('404'));
    }
}
